package pkg

import (
	"os"
	"reflect"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/rs/zerolog/log"
	"notabug.org/BigWaffleMonster/ip-checker-telegram-bot/pkg/controller"
	datatypes "notabug.org/BigWaffleMonster/ip-checker-telegram-bot/pkg/dataTypes"
)

func TelegramBot(controllers *controller.Controller) {
	var ip string
	bot, err := tgbotapi.NewBotAPI(os.Getenv("TOKEN"))
	if err != nil {
		log.Error().Err(err).Msg("Cannot connect to bot")
	}

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message == nil {
			continue
		}

		if reflect.TypeOf(update.Message.Text).Kind() == reflect.String && update.Message.Text != "" {

			switch update.Message.Text {
			case "/start":
				msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Hi")
				bot.Send(msg)

			case "/check_ip":
				msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Enter IP")
				bot.Send(msg)

			case "/get_history":

			default:
				ip = update.Message.Text

				checkResult := CheckIPAddress(ip)

				if checkResult {
          err, msg, data := controllers.GetIpInfo(update.Message.Text)

          if data == (datatypes.IpResponseType{}) {
            msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Empty data from ip")
            bot.Send(msg)
          }

          if err != nil {
            msg := tgbotapi.NewMessage(update.Message.Chat.ID, msg.ErrorMessage)
            bot.Send(msg)
          }

          responseMessage := controllers.MakeResponseMessage(data)

          botMessage := tgbotapi.NewMessage(update.Message.Chat.ID, responseMessage)
          bot.Send(botMessage)

				} else {
					msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Invalid IP")
					bot.Send(msg)
				}
			}
		}
	}
}
